package com.mohan.aop.impl;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ThreadScope implements Scope {
    public static final String THREAD_SCOPE = "thread";

    private ThreadLocal<Map<String,Object>> beanMap = ThreadLocal.withInitial(()->new HashMap<>());

    /**
     * 返回当前作用于bean镀锡
     * @param name 名称
     * @param objectFactory 如果name对应的bean对象在当前作用域没有找到，那么可以调用这个方法来创建对象
     * @return
     */
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object bean = beanMap.get().get(name);
        if (Objects.isNull(bean)) {
            bean = objectFactory.getObject();
            beanMap.get().put(name,bean);
        }
        return bean;
    }

    /**
     * 移除bean中的对象
     * @param name
     * @return
     */
    @Override
    public Object remove(String name) {
        return beanMap.get().remove(name);
    }

    /**
     * 用于注销销毁回调，若想要销毁响应的队，则由Spring容器注册响应的销毁回调，而由自定义作用域选择是不是要销毁响应的对象
     * @param name
     * @param runnable
     */
    @Override
    public void registerDestructionCallback(String name, Runnable runnable) {
        System.out.println("name = " + name);
    }

    /**
     * 用于解析响应的上下文数据，比如request作用域将返回request中的属性
     * @param key
     * @return
     */
    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    /**
     * 用于作用域绘画表示，比如session中的标识是sessionId
     * @return
     */
    @Override
    public String getConversationId() {
        return Thread.currentThread().getName();
    }
}
